package com.ibiz.webapp.controller.bx;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.sql.Timestamp;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonProperty.Access;
import com.ibiz.ibizutil.domain.ActionResult;
import com.ibiz.bx.service.BXDService;
import com.ibiz.ibizutil.domain.AutoCompleteItem;
import com.ibiz.bx.domain.BXD;
import com.ibiz.bx.service.dto.BXDSearchFilter;
import com.ibiz.webapp.controller.bx.vo.*;
import org.springframework.cglib.beans.BeanGenerator;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.util.StringUtils;
import java.io.IOException;
import com.ibiz.ibizutil.errors.BadRequestAlertException;
import org.springframework.validation.annotation.Validated;
import org.springframework.http.ResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import com.ibiz.ibizutil.domain.RedirectResult;
import javax.validation.constraints.NotBlank;
import com.ibiz.ibizutil.domain.AutoCompleteItem;
import java.math.BigInteger;
import com.alibaba.fastjson.JSONObject;
import com.ibiz.workflow.WFServiceImpl;
import com.ibiz.ibizutil.security.AuthenticationUser;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import com.alibaba.fastjson.JSONArray;
import org.flowable.bpmn.model.SequenceFlow;

@RestController
@RequestMapping("/webapp/bx/bxd")
public class BXDController{


	private String strWorkflowKey = "BX" ;

	@Autowired
	WFServiceImpl wfServiceImpl ;

		@GetMapping(value = "wfdiagram")
	public ResponseEntity<byte[]> wfDiagram(@Validated @NotBlank(message = "srfkey不允许为空") @RequestParam("srfkey") String srfkey) {
		InputStream stream = wfServiceImpl.getProcessInstanceDiagram(strWorkflowKey, srfkey) ;

		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.set("Content-Type", "image/png");
		try {
			if(stream!=null)
				return new ResponseEntity<>(org.apache.commons.io.IOUtils.toByteArray(stream), responseHeaders, HttpStatus.OK);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null ;
	}
	
	@GetMapping(value = "his")
	public ResponseEntity<JSONArray> wfHis(@Validated @NotBlank(message = "srfkey不允许为空") @RequestParam("srfkey") String srfkey) {
		JSONArray json = new JSONArray() ;

		return ResponseEntity.ok().body(json);
	}
	
	@GetMapping(value = "wflinks")
	public ResponseEntity<JSONArray> wfLinks(@Validated @NotBlank(message = "srfkey不允许为空") @RequestParam("srfkey") String srfkey) {
		JSONArray jsonArray = new JSONArray() ;
		List<SequenceFlow> flowElements = wfServiceImpl.findTaskLinkByUser(strWorkflowKey, srfkey, AuthenticationUser.getAuthenticationUser().getUserid()) ;
		for (SequenceFlow sequenceFlow : flowElements) {
			JSONObject json = new JSONObject();
			json.put("id", sequenceFlow.getId()) ;
			json.put("name", sequenceFlow.getName());
			if(StringUtils.isEmpty(sequenceFlow.getAttributeValue("http://flowable.org/bpmn", "approvalOperation"))) {
				json.put("type", "BACKEND") ;
			}else {
				json.put("type", "FRONT") ;
				json.put("page", sequenceFlow.getAttributeValue("http://flowable.org/bpmn", "approvalOperation")) ;
				json.put("mobpage", sequenceFlow.getAttributeValue("http://flowable.org/bpmn", "approvalMobOperation")) ;
			}
			
			jsonArray.add(json);	
		}
		return ResponseEntity.ok().body(jsonArray);
	}
	
	@PostMapping(value = "wflink")
	public ResponseEntity<JSONObject> wfLink(@RequestBody JSONObject request) {

		JSONObject ret = new JSONObject() ;
		if(!request.containsKey("args")) {
			ret.put("ret", "902") ;
			ret.put("errorInfo", "处理参数有误") ;
			return ResponseEntity.ok().body(ret);
		}
		JSONObject params = request.getJSONObject("args") ;
		String srfkey = request.getString("srfkey") ;
		String strLink = request.getString("link") ;
		
		if(params==null || StringUtils.isEmpty(srfkey)||StringUtils.isEmpty(strLink)) {
			ret.put("ret", "902") ;
			ret.put("errorInfo", "处理参数有误") ;
			return ResponseEntity.ok().body(ret);
		}
		
    	
    	params.put("ACTION", strLink) ;
    	try {
    		wfServiceImpl.execTask("complete", strWorkflowKey, srfkey, AuthenticationUser.getAuthenticationUser().getUserid(), params);
    		ret.put("ret", "0") ;
    		return ResponseEntity.ok().body(ret);
    	}
		catch (Exception e) {
			ret.put("ret", "903") ;
			ret.put("errorInfo", "处理参数有误") ;
			return ResponseEntity.ok().body(ret);
		}

	}

    @Autowired
	private BXDService bxdService;
	/**
	 * 获取服务对象
	*/
	protected BXDService getService(){
		return this.bxdService;
	}
	/**
	 * 重定向视图
	 * @param srfkey
	 * @return
	 */
	@GetMapping(value="bxdredirectview")
	public ResponseEntity<RedirectResult>bxdredirectviewGet(@Validated @NotBlank(message = "srfkey不允许为空") @RequestParam("srfkey")String srfkey) {
		RedirectResult redirectResult = new RedirectResult();
		return ResponseEntity.ok(redirectResult);
	}


	//FORM FORM  form
	@PostMapping(value = "maineditform/wfstart")
	public ResponseEntity<BXD_EditForm_Main> mainEditFormStart(@Validated @RequestBody BXD_EditForm_Main form) {
		BXD entity =form.toBXD();
        getService().save(entity);
        form.fromBXD(entity);
		form.setSrfuf("1");
    	
		try {
			JSONObject params = new JSONObject();
	    	wfServiceImpl.start(AuthenticationUser.getAuthenticationUser().getUserid(), strWorkflowKey, entity.getBxdid(), params) ;
			return ResponseEntity.ok().body(form);
    	}
		catch (Exception e) {
			e.printStackTrace();
			throw new BadRequestAlertException("启动流程异常","111","900") ;
		}
	}


	@PostMapping(value="maineditform/update")
	public ResponseEntity<BXD_EditForm_Main> mainEditFormUpdate(@Validated @RequestBody BXD_EditForm_Main form){
            BXD entity =form.toBXD();
            getService().update(entity);
            form.fromBXD(entity);
            form.setSrfuf("1");
            return ResponseEntity.ok().body(form);
	}
	@GetMapping(value="maineditform/remove")
	public ResponseEntity<BXD_EditForm_Main> mainEditFormRemove(@Validated @NotBlank(message = "srfkey不允许为空") @RequestParam("srfkey")String srfkey){
            BXD_EditForm_Main form=new BXD_EditForm_Main();
            BXD entity = new BXD();
            entity.setBxdid(srfkey);
            getService().remove(entity);
            form.setSrfuf("0");
            form.fromBXD(entity);
            return ResponseEntity.ok().body(form);
	}
	@PostMapping(value="maineditform/getdraft")
	public ResponseEntity<BXD_EditForm_Main> mainEditFormGetDraft(@RequestBody BXD_EditForm_Main form){
        if(!StringUtils.isEmpty(form.getSrfsourcekey()))
        {
            BXD sourceEntity =new BXD();
            sourceEntity.setBxdid(form.getSrfsourcekey());
            this.getService().get(sourceEntity);

			BXD targetEntity =new BXD();
			sourceEntity.copyTo(targetEntity);
			form.fromBXD(targetEntity,false);
            form.setSrfuf("0");
            return ResponseEntity.ok().body(form);
         }
            BXD entity =form.toBXD();
            getService().getDraft(entity);
            form.fromBXD(entity);
            form.setSrfuf("0");
            return ResponseEntity.ok().body(form);
	}
	@GetMapping(value="maineditform/get")
	public ResponseEntity<BXD_EditForm_Main> mainEditFormGet(@Validated @NotBlank(message = "srfkey不允许为空") @RequestParam("srfkey")String srfkey){
            BXD_EditForm_Main form=new BXD_EditForm_Main();
            BXD entity = new BXD();
            entity.setBxdid(srfkey);
            entity=getService().get(entity);
            form.setSrfuf("1");
            form.fromBXD(entity);
            return ResponseEntity.ok().body(form);
	}
	@PostMapping(value="maineditform/create")
	public ResponseEntity<BXD_EditForm_Main> mainEditFormCreate(@Validated @RequestBody BXD_EditForm_Main form){
            BXD entity =form.toBXD();
            getService().create(entity);
            form.fromBXD(entity);
            form.setSrfuf("1");
            return ResponseEntity.ok().body(form);
	}









	@PostMapping(value="maingrid/update")
	public BXD mainGridUpdate(@Validated BXD mainItem){
		return mainItem;
	}
	@PostMapping(value="maingrid/remove")
	public ResponseEntity<BXD> mainGridRemove(@Validated @RequestBody Map args){
	    BXD entity =new BXD();
	    if ( !StringUtils.isEmpty(args.get("srfkeys"))) {
			String srfkeys=args.get("srfkeys").toString();
			String srfkeyArr[] =srfkeys.split(";");
			for(String srfkey : srfkeyArr)
			{
				if(!StringUtils.isEmpty(srfkey)){
				entity.setBxdid(srfkey);
				this.getService().remove(entity);
                }
            }
        }
		return ResponseEntity.ok().body(entity);
	}
	public BXD mainGridGet(String bxdid){
		return null;
	}
	@PostMapping(value="maingrid/getdraft")
	public BXD mainGridGetDraft(@Validated BXD mainItem){
		return mainItem;
	}
	@PostMapping(value="maingrid/create")
	public BXD mainGridCreate(@Validated BXD mainItem){
		return mainItem;
	}
	@org.springframework.beans.factory.annotation.Value("${ibiz.filePath}")
    private String strFilePath;
	@Autowired
    private com.ibiz.ibizutil.service.IBZFILEService ibzfileService;
	/**
	 * [main]表格数据导出
	 * @param searchFilter
	 * @return
	 * @throws
	 * @throws
	 */
	@PostMapping(value="maingrid/exportdata/searchdefault")
	public ResponseEntity<Page<JSONObject>> maingridExportDataSearchDefault(@Validated @RequestBody BXDSearchFilter searchFilter) throws IOException, jxl.write.WriteException {
		String fileid=com.baomidou.mybatisplus.core.toolkit.IdWorker.get32UUID();
		String localPath=ExportDataInit(fileid);//输出文件相对路径
		Page<BXD> searchResult = this.getService().searchDefault(searchFilter);//1.查询表格数据
		List<Map<String,Object>> datas=BXD_Grid_Main.pageToListDatas(searchResult);//2.将数据转换成list
		List<Map<String,String>> colnums=BXD_Grid_Main.getGridColumnModels();//3.获取表格列头
        java.io.File outputFile=com.ibiz.ibizutil.helper.DEDataExportHelper.output(strFilePath+localPath,colnums,datas);//4.生成导出文件
		com.ibiz.ibizutil.helper.DEDataExportHelper.saveFileData(outputFile,localPath,fileid,ibzfileService); //5.保存file表记录
		String strDownloadUrl =String.format("ibizutil/download/"+fileid);//6.回传文件路径给前台
        Page<JSONObject> resultObj=BXD_Grid_Main.getResultPage(searchResult,strDownloadUrl);//7.获取输出对象
			return ResponseEntity.ok().body(resultObj);
	}
	/**
	 * 表格数据导出
	 * @param fileid
	 * @return
	 */
	private String ExportDataInit(String fileid) {
		java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyyMMdd");
        String filepath=dateFormat.format(new java.util.Date())+ java.io.File.separator;
        java.text.SimpleDateFormat dateFormat2 = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
		String strTempFileName = fileid+"-"+dateFormat2.format(new java.util.Date())+".xls";
		java.io.File file =new java.io.File(strFilePath+filepath);
		if(!file.exists())
           file.mkdirs();
		return filepath+strTempFileName;
	}
	@PostMapping(value="maingrid/searchdefault")
	public ResponseEntity<Page<BXD_Grid_Main>> mainGridSearchDefault(@Validated @RequestBody BXDSearchFilter searchFilter){
			Page<BXD> searchResult = this.getService().searchDefault(searchFilter);
			Page<BXD_Grid_Main> searchResult_vo_data =BXD_Grid_Main.fromBXD(searchResult);
					return ResponseEntity.ok().body(searchResult_vo_data);
	}
	@PostMapping(value="defaultsearchform/load")
	public void defaultSearchFormLoad(){

	}
   	@PostMapping(value="defaultsearchform/loaddraft")
	public ResponseEntity<BXD_SearchForm_Default> defaultSearchFormLoadDraft(@Validated @RequestBody BXD_SearchForm_Default searchform){
 		 
			BXDSearchFilter searchfilter =searchform.toBXDSearchFilter();
			searchform.fromBXDSearchFilter(searchfilter);
			return ResponseEntity.ok().body(searchform);
	} 
	@PostMapping(value="defaultsearchform/search")
	public void defaultSearchFormSearch(){
			 
	} 
 }